package com.axjy.controller;

import com.axjy.pojo.Role;
import com.axjy.service.RoleService;
import com.axjy.util.Result;
import com.axjy.vo.TreeNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.jws.WebParam;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
@Slf4j
public class RoleController {

    @Resource
    private RoleService roleService;

    private String msg;

//    @GetMapping("/index")
//    public ModelAndView index(){
//        return new ModelAndView("sys/role");
//    }

    @GetMapping("/search")
    public Result search(){
        List<Role> list=roleService.searchList();
        return Result.success(list);
    }

    @PostMapping("/update")
    public Result update(Role role){
        try {
            roleService.update(role);
            msg="角色修改成功!";
            return Result.success(msg);
        }catch (Exception ex){
            msg="角色修改失败!";
            log.error(msg,ex);
            return Result.fail(msg);
        }
    }

    @PostMapping("/add")
    public Result add(Role role){
        try {
            roleService.add(role);
            msg="角色添加成功!";
            return Result.success(msg);
        }catch (Exception ex){
            msg="角色添加失败!";
            log.error(msg,ex);
            return Result.fail(msg);
        }
    }

    //路径变量
    @GetMapping("/del/{id}")
    public Result del(@PathVariable Integer id){
        try {
            roleService.del(id);
            msg="角色删除成功!";
            return Result.success(msg);
        }catch (Exception ex){
            msg="角色删除失败!";
            log.error(msg,ex);
            return Result.fail(msg);
        }
    }

    @GetMapping("/searchTreeData/{id}")
    public Result searchTreeData(@PathVariable Integer id){
      List<TreeNode> list= roleService.searchTreeData(id);
      return Result.success(list);
    }

    @PostMapping("/grant")
    public Result grant(Integer roleId,Integer[] ids){
        try {
            roleService.grant(roleId,ids);
            msg="角色授权成功!";
            return Result.success(msg);
        }catch (Exception ex){
            msg="角色授权失败!";
            log.error(msg,ex);
            return Result.fail(msg);
        }
    }


}
